package com.ciwong.epaper.modules.epaper.ui.newlistenspeak.longcoversation;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.Attachments;
import com.ciwong.epaper.modules.epaper.bean.OptionDetail;
import com.ciwong.epaper.modules.epaper.bean.OptionInfo;
import com.ciwong.epaper.modules.epaper.bean.QuestionScore;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by keepon on 2018/4/28.
 */

public class ChildQuestionLayout extends LinearLayout {
    private TextView tvChildStem;
    private LinearLayout optionsLayout;
    protected String[] optionHeads = new String[]{"A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
            "T", "U", "V", "W", "X", "Y", "Z"};
    private boolean mAllowAnswer = false;
    protected View oldSelectedView = null;

    public ChildQuestionLayout(Context context) {
        this(context, null);
    }

    public ChildQuestionLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChildQuestionLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutInflater.from(this.getContext()).inflate(R.layout.child_question_layout, this);
        tvChildStem = (TextView) findViewById(R.id.child_quesion_stem);// 子题题干
        optionsLayout = (LinearLayout) findViewById(R.id.question_options);// 小题选项
    }

    public void setChildContent(Questions childQuestion, int childIndex, LswAnswer lswAnswer, ResourceDetail resourceDetail) {
        OptionDetail optionsDetail = childQuestion.getTrunk();
        String textTitle;
        String textScore = ListenSpeakUtil.getChildQuestionScore(childQuestion, resourceDetail.getScores());
        if (childQuestion.getSort() != null && !"".equals(childQuestion.getSort())) {
            textTitle = childQuestion.getSort() + "、" + textScore + optionsDetail.getBody();
        } else {
            textTitle = optionsDetail.getBody();
            if (!"".equals(textScore)) {
                if (!"".equals(textScore)) {
                    StringBuffer stringBuffer = new StringBuffer(textTitle);
                    stringBuffer.insert(2, textScore);
                    textTitle = stringBuffer.toString();
                }
            } else {
                textTitle = textScore;
            }
        }
        setChildQuestionStem(textTitle);
        loadChildOptionLayout(childQuestion, childQuestion.getOptions(), childQuestion.getType(), childIndex, lswAnswer);
    }

    /**
     * 加载子题题干
     * type=5 显示小题序号 小题提干
     *
     * @param text
     */
    public void setChildQuestionStem(String text) {
        if (TextUtils.isEmpty(text)) {
            tvChildStem.setVisibility(View.GONE);
        } else {
            if (!TextUtils.isEmpty(text)) {
                text = text.replace("\n", "<br>");
            }
            tvChildStem.setText(Html.fromHtml(text));
            tvChildStem.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 加载选项布局
     *
     * @param optionInfoList
     */
    public void loadChildOptionLayout(final Questions childQuestion, final List<OptionInfo> optionInfoList, final int mQuestionType, final int childIndex, final LswAnswer lswAnswer) {

        int topBottom1 = DeviceUtils.dip2px(3);
        LayoutParams params1 = new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params1.setMargins(0, topBottom1, 0, topBottom1);

        for (int i = 0; optionInfoList != null
                && i < optionInfoList.size(); i++) {

            final OptionInfo optionInfo = optionInfoList.get(i);

            final View container = View.inflate(getContext(),
                    R.layout.item_listen_speak_view, null);

            final LinearLayout itemView = (LinearLayout) container
                    .findViewById(R.id.item_ls_view);

            final LinearLayout itemBody = (LinearLayout) View.inflate(getContext(),
                    R.layout.item_listen_speak_body, itemView);

            final TextView itemBtn = (TextView) itemBody
                    .findViewById(R.id.item_left_btn);

            final EditText itemText = (EditText) itemBody
                    .findViewById(R.id.item_options_tv);

            final ImageView itemImg = (ImageView) itemBody
                    .findViewById(R.id.item_img);


            final int index = i;

            itemBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    container.performClick();
                }
            });
            container.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (v.equals(oldSelectedView)) {
                        return;
                    }
                    //没有播放请开始答题的提示音之前不允许答题
                    if (!mAllowAnswer && lswAnswer == null) {
                        return;
                    }

                    if (oldSelectedView != null) {
                        oldSelectedView.setSelected(false);
                        itemBtn.setSelected(false);
                    }

                    container.setSelected(true);
                    itemBtn.setSelected(true);
                    oldSelectedView = container;
                    if (mOnChildCheckListener != null) {
                        mOnChildCheckListener.onChildChecked(childQuestion, childQuestion.getVersionId(), optionInfo.getId(), childIndex, index);
                    }
                }
            });

            if (optionInfo != null) {
                List<OptionDetail> optionDetailList = optionInfo.getValue();
                if (optionDetailList != null && !optionDetailList.isEmpty()) {
                    OptionDetail optionDetail = optionDetailList.get(0);
                    if (optionDetail != null
                            && optionDetail.getBody() != null) {
                        String body = optionDetail.getBody();
                        //选择题
                        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE) {
                            itemBtn.setText(optionHeads[i]);
                            if (!TextUtils.isEmpty(body)) {
                                itemText.setText(body);
                            } else {
                                itemText.setVisibility(View.GONE);
                            }
                            itemText.setEnabled(false);
                        }

                        // 加载附件里的图片
                        List<Attachments> attachmentList = optionDetail
                                .getAttachments();
                        if (attachmentList != null
                                && !attachmentList.isEmpty()) {
                            Attachments attachments = attachmentList.get(0);
                            final String url = attachments.getUrl();
                            if (!TextUtils.isEmpty(url)) {
                                switch (attachments.getFileType()) {
                                    case Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_IMG:// 图片
                                        itemImg.setOnClickListener(
                                                new OnClickListener() {
                                                    @Override
                                                    public void onClick(
                                                            View v) {
                                                        ArrayList<String> urlList = new ArrayList<String>();
                                                        urlList.add(ESystem.formatPath(url));
                                                        BaseJumpManager.jumpToScanImage((Activity) getContext(), R.string.listen_speak, urlList, 0);
                                                    }
                                                });
                                        ImageLoader.getInstance().displayImage(ESystem.formatPath(url), itemImg);
                                        itemImg.setVisibility(View.VISIBLE);
                                        break;
                                    case Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_AUDIO:// 语音
                                        break;
                                }
                            }
                        }
                        optionsLayout.setVisibility(VISIBLE);
                        optionsLayout.addView(container);

                        if (optionInfo != null && lswAnswer != null && lswAnswer.getAnswerContents() != null && lswAnswer.getAnswerContents().size() > 0) {
                            if (lswAnswer.getAnswerContents().get(0).getContent().equals(optionInfo.getId())) {
                                container.performClick();
                            }
                        }
/*
						if (i == optionInfoList.size() - 1) {
							container.findViewById(R.id.item_line)
									.setVisibility(View.VISIBLE);
						}*/

                    }
                }
            }
        }
    }

    public void setOnChildCheckListener(OnChildCheckListener onChildCheckListener) {
        mOnChildCheckListener = onChildCheckListener;
    }

    OnChildCheckListener mOnChildCheckListener;

    interface OnChildCheckListener {
        void onChildChecked(Questions childQuestion, String questionVersionId, String answerId, int childIndex, int indexSelected);
    }

    public void allowAnswer(boolean allowAnswer) {

        mAllowAnswer = allowAnswer;

    }


}
